<?php

namespace Wgx\Admin\Controller;


use Wgx\Admin\Com\AdminMenuRightsUtil;
use Wgx\Admin\Com\AdminSession;
use Wgx\Admin\Com\Crud\Crud;
use Wgx\Admin\Com\NoMenuRightException;
use Wgx\Admin\Com\NotLoginException;
use Wgx\Admin\Entity\AdminToMenuEntity;
use PhpYes\Entity\BaseEntity;

abstract class BaseController
{

    const AuthNone = 0;
    const AuthLogin = 0b00000001; // 1
    const AuthAdminMenu = 0b00000010; // 2

    protected $auth = self::AuthLogin | self::AuthAdminMenu;

    /**
     * @throws NotLoginException
     * @throws NoMenuRightException
     * @throws \Exception
     */
    public function preflight()
    {
        $this->auth = empty($this->auth) ? 0 : intval($this->auth);
        if ($this->auth) {
            $isAuthLogin = $this->auth & self::AuthLogin;
            if ($isAuthLogin) {
                $adminUserEntity = AdminSession::getSingleObj()->getAdminUserEntity();
                if (empty($adminUserEntity)) {
                    throw new NotLoginException();
                }

                $isAuthMenu = $this->auth & self::AuthAdminMenu;
                if ($isAuthMenu) {
                    $method = \PhpYes\Apps::getReqMethod();
                    if (empty(AdminToMenuEntity::$methodNeedRightMap[$method])) {
                        throw new NoMenuRightException(); // 非法Method(非法操作),借用一下NoMenuRightException,免得再定义一个异常,毕竟这种情况很少,几乎不可能发生
                    }
                    $methodNeedRight = AdminToMenuEntity::$methodNeedRightMap[$method];
                    $rights = AdminMenuRightsUtil::getSingleObj()->getCurrentRights();
                    if ($rights < 1 || ($rights & $methodNeedRight) < 1) {
                        throw new NoMenuRightException();
                    }
                }
            }
        }
    }

    /**
     * throws \Wgx\Admin\Com\Crud\InvalidFieldValueException 来指示某个字段的值设置的不正确
     * @param Crud $crud
     * @param BaseEntity $entity - $entity = $crud->entityTpl->newObject(); or $entity = $crud->entityTpl->findById($id);
     * @param array $data - 客户端提交到服务器的数据
     * @throws \Exception
     */
    public function createOrUpdate(Crud $crud, BaseEntity $entity, $data)
    {
        throw new \Exception('You should override this function');
    }

    /**
     * @param Crud $crud
     * @param int[] $ids
     */
    public function deleteByIds(Crud $crud, $ids)
    {
        if (empty($ids)) {
            return;
        }

        $cnt = count($ids);
        if ($cnt == 1) {
            $crud->getEntityTpl()->deleteById($ids[0]);
        } else {
            $crud->getEntityTpl()->deleteByIds($ids);
        }
    }

}